package com.ruoyi.article.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.article.domain.vo.ArticleVO;
import com.ruoyi.category.domain.ArticleCategory;
import com.ruoyi.category.service.IArticleCategoryService;
import com.ruoyi.comment.domain.Comment;
import com.ruoyi.comment.service.ICommentService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.article.domain.Article;
import com.ruoyi.article.service.IArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文章管理Controller
 *
 * @author ruoyi
 * @date 2025-05-22
 */
@RestController
@RequestMapping("/article/article")
public class ArticleController extends BaseController {
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArticleCategoryService articleCategoryService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ICommentService commentService;
    /**
     * 查询文章管理列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(Article  article) {
        System.out.println(article);

        startPage(article.getPageNum(), article.getPageSize());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        article .setUserId(user.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        List<ArticleVO> list;
        if (roles.contains("common")) {
            list = articleService.selectByUseridArticleVO(article);
        } else {
            list = articleService.selectArticeVO(article);
        }
//        List<ArticleVO> filteredList = list.stream()
//                .filter(articleVO -> {
//                    boolean titleMatch = article.getTitle() == null || articleVO.getTitle().contains(article.getTitle());
//                    boolean statusMatch = article.getStatus() == null || articleVO.getStatus().equals(article.getStatus());
//                    boolean categoryIdMatch = article.getCategoryId() == null;
//                    if (!categoryIdMatch) {
//                        ArticleCategory articleCategory = articleCategoryService.selectArticleCategoryByCategoryId(article.getCategoryId());
//                        categoryIdMatch = articleVO.getCategoryId().equals(articleCategory.getCategoryName());
//                    }
//                    return titleMatch && statusMatch && categoryIdMatch;
//                })
//                .collect(Collectors.toList());

        return getDataTable(list);
    }

    //根据分类id查询文章
    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @GetMapping("/listByCategoryId")
    public TableDataInfo listByCategoryId(Article article) {
        startPage(article.getPageNum(), article.getPageSize());
        List<ArticleVO> list = articleService.selectArticleByCategoryId(article.getCategoryId());
        List<ArticleVO> list1 = new ArrayList<>();
        for (ArticleVO articleVO : list) {
            if (articleVO.getStatus().equals("已审核")) {
                Comment comment = new Comment();
                comment.setArticleId(articleVO.getArticleId());
                List<Comment> comments =commentService.selectCommentList(comment);
                articleVO.setCommentCount((long) comments.size());
                list1.add(articleVO);
            }
        }
        return getDataTable(list1);
    }

    /**
     * 导出文章管理列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:export')")
    @Log(title = "文章管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Article article) {
        List<Article> list = articleService.selectArticleList(article);
        ExcelUtil<Article> util = new ExcelUtil<Article>(Article.class);
        util.exportExcel(response, list, "文章管理数据");
    }

    /**
     * 获取文章管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:article:query')")
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId) {
        Integer count = redisCache.getCacheObject("article:click-count:" + articleId);
        if (count == null || count == 0) {
            redisCache.setCacheObject("article:click-count:" + articleId, 1);
        } else {
            redisCache.setCacheObject("article:click-count:" + articleId, count + 1);
        }

        // 记录被访问的文章ID到集合中
        Set<Long> setcount = redisCache.getCacheSet("article:");
         if (setcount == null) {
            setcount = new java.util.HashSet<>();
        }
        setcount.add(articleId);
        redisCache.setCacheSet("article:", setcount);

        return success(articleService.selectArticleVoByArticleId(articleId));
    }

    /**
     * 新增文章管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "文章管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Article article) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        article.setUserId(user.getUserId());
        article.setClickCount(0L);

        return toAjax(articleService.insertArticle(article));
    }

    /**
     * 修改文章管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "文章管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ArticleVO articleVO) {
        Article  article = new Article();
        BeanUtils.copyProperties(articleVO,article);
        if(articleVO.getCategoryId()!=null)
        article.setCategoryId(Long.valueOf(articleVO.getCategoryId()));
        return toAjax(articleService.updateArticle(article));
    }

    /**
     * 删除文章管理
     */
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @Log(title = "文章管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds) {
        return toAjax(articleService.deleteArticleByArticleIds(articleIds));
    }
}
